package cn.sdhuijin.mediaplatform;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年3月25日 上午9:11:36 webView加载农信wap网站
 */
public class WebViewActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();
	private static final String APP_CACAHE_DIRNAME = "/webcache";
	private WebView mWebView;
	private String url;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		url = "http://wap.sdrcu.com/pwap/index.jsp";
		findView();
	}

	private void findView() {
		mWebView = (WebView) findViewById(R.id.webview);
		initWebView();
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView webview, String url) {
				webview.loadUrl(url);
				return true;
			}
		});

		mWebView.loadUrl(url);
	}

	private void initWebView() {
		mWebView.setInitialScale(215);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); // 设置
																		// 缓存模式
		int screenDensity = getResources().getDisplayMetrics().densityDpi;
		WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
		switch (screenDensity) {
		case DisplayMetrics.DENSITY_LOW:
			zoomDensity = WebSettings.ZoomDensity.CLOSE;
			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			zoomDensity = WebSettings.ZoomDensity.MEDIUM;
			break;
		case DisplayMetrics.DENSITY_HIGH:
			zoomDensity = WebSettings.ZoomDensity.FAR;
			break;
		}
		mWebView.getSettings().setDefaultZoom(zoomDensity);

		// 开启 DOM storage API 功能
		mWebView.getSettings().setDomStorageEnabled(true);
		// 开启 database storage API 功能
		mWebView.getSettings().setDatabaseEnabled(true);
		String cacheDirPath = getFilesDir().getAbsolutePath()
				+ APP_CACAHE_DIRNAME;
		// 设置数据库缓存路径
		mWebView.getSettings().setDatabasePath(cacheDirPath);
		// 设置 Application Caches 缓存目录
		mWebView.getSettings().setAppCachePath(cacheDirPath);
		// 开启 Application Caches 功能
		mWebView.getSettings().setAppCacheEnabled(true);
	}

	/**
	 * 清除WebView缓存
	 */
	public void clearWebViewCache() {
		// 清理Webview缓存数据库
		try {
			deleteDatabase("webview.db");
			deleteDatabase("webviewCache.db");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// WebView 缓存文件
		File appCacheDir = new File(getFilesDir().getAbsolutePath()
				+ APP_CACAHE_DIRNAME);
		File webviewCacheDir = new File(getCacheDir().getAbsolutePath()
				+ "/webviewCache");
		// 删除webview 缓存目录
		if (webviewCacheDir.exists()) {
			deleteFile(webviewCacheDir);
		}
		// 删除webview 缓存 缓存目录
		if (appCacheDir.exists()) {
			deleteFile(appCacheDir);
		}
	}

	/**
	 * 递归删除 文件/文件夹
	 * 
	 * @param file
	 */
	public void deleteFile(File file) {

		Log.i(TAG, "delete file path=" + file.getAbsolutePath());

		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
			Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
		}
	}

	/**
	 * 删除Cookie
	 */
	private void removeCookie() {
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieManager.getInstance().removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		CookieSyncManager.getInstance().startSync();
	}

	/**
	 * 按键响应，在WebView中查看网页时，按返回键的时候按浏览历史退回,如果不做此项处理则整个WebView返回退出
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Check if the key event was the Back button and if there's history
		// if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
		// // 返回键退回
		// mWebView.goBack();
		// return true;
		// }
		new AlertDialog.Builder(this)
				.setTitle("提示")
				.setMessage("确定退出农村信用社WAP版吗？")
				.setPositiveButton("是", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						clearWebViewCache();
						removeCookie();
						WebViewActivity.this.finish();
					}
				})
				.setNegativeButton("否", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
					}
				}).show();
		return super.onKeyDown(keyCode, event);
	}
}
